﻿using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using VitCode.Castle.Helper;
using VitCode.Web.UI;
using VitCode.Web.UI.WebControls;

namespace AMS.Web
{
    public partial class ConditionSelector : Page
    {
        private string _conditionTable = String.Empty;
        private string _condtionUser = String.Empty;
        private ConditionManager manager;

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = 0;
            if (Request.QueryString["ConditionUser"] == null || Request.QueryString["ConditionUser"].Length == 0)
                _condtionUser = "Everyone";
            else
                _condtionUser = Request.QueryString["ConditionUser"].ToString();
            if (Request.QueryString["ConditionTable"] == null ||
                Request.QueryString["ConditionTable"].ToString().Length == 0)
                throw new ArgumentNullException("ConditionTable", "没有指明条件表");
            else
                _conditionTable = Request.QueryString["ConditionTable"].ToString();
            if (!IsPostBack)
            {
                manager = new ConditionManager(_condtionUser, _conditionTable);
                BindFieldList();
                BindOperatorList();
                BindJoinOperatorList();
                Btn_Cancel.Attributes.Add("onclick", "javascript:OnCancel()");
                Session["ConditionManager"] = null;
                Session["ConditionManager"] = manager;
                BindConditionList();
            }
            else
            {
                manager = Session["ConditionManager"] as ConditionManager;
            }
        }

        protected void Btn_AddCondition_Click(object sender, EventArgs e)
        {
            string fieldvalue = "";
            if (Panel_ConditionValue.Visible)
            {
                fieldvalue = Txt_FieldValue.Text;
                Txt_FieldValue.Text = "";
            }
            else
            {
                if ((!IsNumeric(Txt_FieldBeginRange.Text) || !IsNumeric(Txt_FieldEndRange.Text)) &&
                    (!IsDateTime(Txt_FieldBeginRange.Text) || !IsDateTime(Txt_FieldEndRange.Text)))
                {
                    MessageBox.Show("条件的起始值或结束值只能是数字或日期");
                    return;
                }
                fieldvalue = Txt_FieldBeginRange.Text + "," + Txt_FieldEndRange.Text;
                Txt_FieldBeginRange.Text = Txt_FieldEndRange.Text = "";
            }
            if (IsPossibleDateTime(fieldvalue, ".") || IsPossibleDateTime(fieldvalue, "-"))
            {
                if (!IsDateTime(fieldvalue))
                {
                    MessageBox.Show("不是正确的日期格式，请输入形如：2006.01.01 的日期格式");
                    return;
                }
            }
            if (IsPossibleDateTime(fieldvalue))
            {
                string temp = fieldvalue.Replace("年", ".");
                temp = temp.Replace("月", ".");
                temp = temp.Replace("日", "");
                if (!IsDateTime(temp))
                {
                    MessageBox.Show("不是正确的日期格式。");
                    return;
                }
                else
                    fieldvalue = temp;
            }
            if (manager.ConditionCollection.Count > 0)
            {
                if (Lst_JoinOperator.SelectedIndex == 0)
                {
                    MessageBox.Show("请选择当前条件与前一条件的关系!");
                    return;
                }
            }
            var condition = new Condition();
            condition.FieldText = Lst_Field.SelectedItem.Text;
            condition.FieldName = Lst_Field.SelectedValue;
            condition.FieldValue = fieldvalue;
            condition.Operator =
                (ConditionOperatorEnum) Enum.Parse(typeof (ConditionOperatorEnum), Lst_Operator.SelectedValue);
            condition.JoinOperator =
                (ConditionJoinOperatorEnum)
                Enum.Parse(typeof (ConditionJoinOperatorEnum), Lst_JoinOperator.SelectedValue);
            manager.ConditionCollection.Add(condition);
            Lst_Field.SelectedIndex = 0;
            Lst_Operator.SelectedIndex = 0;
            BindConditionList();
            if (manager.ConditionCollection.Count > 0 && Lst_JoinOperator.SelectedValue == ConditionJoinOperatorEnum.NULL.ToString())
                Lst_JoinOperator.SelectedIndex = 1;
            Btn_OK.Enabled = true;
        }

        /// <summary>
        /// 绑定条件字段列表
        /// </summary>
        private void BindFieldList()
        {
            NameValueCollection table = manager.GetFieldList(_conditionTable);
            Lst_Field.DataSource = table;
            for (int i = 0; i < table.Count; i++)
            {
                Lst_Field.Items.Add(new ListItem(table.Keys[i], table.GetValues(table.Keys[i])[0]));
            }
        }

        /// <summary>
        /// 绑定操作符列表
        /// </summary>
        private void BindOperatorList()
        {
            
            string[] operators = Enum.GetNames(typeof (ConditionOperatorEnum));
            Lst_Operator.DataSource = operators;
            Lst_Operator.DataBind();
            foreach(ListItem li in Lst_Operator.Items)
            {
                string strText = EnumTypeHelper.GetEnumDescript(typeof (ConditionOperatorEnum), li.Value);
                li.Text=(strText);
            }
        }

        /// <summary>
        /// 绑定条件连接符列表
        /// </summary>
        private void BindJoinOperatorList()
        {
            string[] operators = Enum.GetNames(typeof (ConditionJoinOperatorEnum));
            Lst_JoinOperator.DataSource = operators;
            Lst_JoinOperator.DataBind();
            Lst_JoinOperator.SelectedIndex = 2;
            foreach (ListItem li in Lst_JoinOperator.Items)
            {
                string strText = EnumTypeHelper.GetEnumDescript(typeof(ConditionJoinOperatorEnum), li.Value);
                li.Text = (strText);
            }
        }

        /// <summary>
        /// 绑定条件列表
        /// </summary>
        private void BindConditionList()
        {
            Lst_ConditionList.Items.Clear();
            ConditionCollection conditionlist = manager.ConditionCollection;
            for (int i = 0; i < conditionlist.Count; i++)
            {
                Lst_ConditionList.Items.Add(new ListItem(conditionlist[i].ToString(),
                                                         conditionlist[i].GetConditioExpression()));
            }
            Btn_ClearCondition.Enabled = Lst_ConditionList.Items.Count > 0;
        }

        private bool IsPossibleDateTime(string text, string speator)
        {
            int a, b;
            bool flag = false;
            a = text.IndexOf(speator, 0);
            if (a == 4)
            {
                b = text.IndexOf(speator, 5);
                if (b == 6 || b == 7)
                {
                    flag = true;
                }
            }
            return flag;
        }

        private bool IsPossibleDateTime(string text)
        {
            int a, b;
            bool flag = false;
            a = text.IndexOf("年", 0);
            if (a == 4)
            {
                b = text.IndexOf("月", 5);
                if (b == 6 || b == 7)
                {
                    if (text.Substring(text.Length - 1, 1) == "日")
                        flag = true;
                }
            }
            return flag;
        }

        private bool IsDateTime(string text)
        {
            try
            {
                Convert.ToDateTime(text);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private bool IsNumeric(string text)
        {
            try
            {
                Convert.ToInt32(text);
                return true;
            }
            catch
            {
                return false;
            }
        }

        protected void Btn_Modify_Click(object sender, EventArgs e)
        {
        }

        protected void Btn_DeleteCondition_Click(object sender, EventArgs e)
        {
            manager.ConditionCollection.Remove(Lst_ConditionList.SelectedIndex);
            BindConditionList();
            Btn_DeleteCondition.Enabled = false;
        }

        protected void Btn_ClearCondition_Click(object sender, EventArgs e)
        {
            manager.ConditionCollection.Clear();
            BindConditionList();
            Btn_DeleteCondition.Enabled = false;
        }

        protected void Btn_OK_Click(object sender, EventArgs e)
        {
            Txt_Condition.Text = manager.GetSpecialyConidtionString();
            if (Chk_SaveCondition.Checked)
            {
                manager.SaveCondition(_condtionUser, _conditionTable);
            }
            var script = new StringBuilder();
            script.Append("<script language=javascript>\n");
            script.Append("window.attachEvent(\"onload\",function(){OnOK()})\n");
            script.Append("</script>\n");
            ClientScript.RegisterStartupScript(GetType(), "OK", script.ToString());
        }

        protected void Btn_Cancel_Click(object sender, EventArgs e)
        {
        }

        protected void Lst_ConditionList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Lst_ConditionList.SelectedItem != null)
            {
                Btn_DeleteCondition.Enabled = true;
                string temp = Lst_ConditionList.SelectedItem.Value;
                var condition = new Condition(temp, ConditionJoinOperatorEnum.NULL);
                Condition condition1 = manager.FindCondition(condition.FieldName, Lst_ConditionList.SelectedIndex);
                if (condition1 != null)
                {
                    Lst_Field.SelectedValue = condition1.FieldName;
                    Lst_Operator.SelectedValue = condition1.Operator.ToString();
                    if (condition1.Operator == ConditionOperatorEnum.JieYu)
                    {
                        Panel_ConditionRange.Visible = true;
                        Panel_ConditionValue.Visible = false;
                        Txt_FieldBeginRange.Text = condition1.FieldValue.Split(',')[0];
                        Txt_FieldEndRange.Text = condition1.FieldValue.Split(',')[1];
                    }
                    else
                    {
                        Panel_ConditionValue.Visible = true;
                        Panel_ConditionRange.Visible = false;
                        Txt_FieldValue.Text = condition1.FieldValue;
                    }
                    Lst_JoinOperator.SelectedValue = condition1.JoinOperator.ToString();
                }
            }
        }

        protected void Lst_Operator_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Lst_Operator.SelectedValue == ConditionOperatorEnum.JieYu.ToString())
            {
                Panel_ConditionRange.Visible = true;
                Panel_ConditionValue.Visible = false;
            }
            else
            {
                Panel_ConditionValue.Visible = true;
                Panel_ConditionRange.Visible = false;
            }
            if (Lst_Operator.SelectedValue == ConditionOperatorEnum.FeiKong.ToString() || Lst_Operator.SelectedValue == ConditionOperatorEnum.WeiKong.ToString())
            {
                Txt_FieldValue.Enabled = false;
                Txt_FieldValue.BackColor = Btn_AddCondition.ControlStyle.BackColor;
            }
            else
            {
                if (Txt_FieldValue.Enabled == false)
                    Txt_FieldValue.Enabled = true;
                Txt_FieldValue.BackColor = Color.White;
            }
        }
    }
}